<template>
  <el-dialog
    title="建立关系"
    :visible.sync="visible"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
    class="relation-dialog"
  >
    <el-form
      ref="relationFormRef"
      :model="relationFormData"
      :rules="relationFormRules"
      label-width="100px"
    >
      <el-form-item label="选择区域" prop="areaId">
        <el-select
          v-model="relationFormData.areaId"
          placeholder="请选择区域"
          style="width: 100%"
          @change="handleAreaChange"
        >
          <el-option
            v-for="item in areaOptions"
            :key="item.pkid"
            :label="item.areaName"
            :value="item.pkid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配置项" prop="serviceIds">
        <div class="config-tree-header">
          <el-checkbox
            v-model="selectAll"
            @change="handleSelectAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
        </div>
        <div class="config-tree-container">
          <el-tree
            ref="configTreeRef"
            :data="configTreeData"
            show-checkbox
            node-key="pkid"
            :props="treeProps"
            :default-checked-keys="relationFormData.serviceIds"
            :default-expand-all="true"
            @check="handleTreeCheck"
          />
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        type="primary"
        @click="handleSubmit"
        :loading="submitLoading"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue'

interface TreeItem {
  pkid: string
  name: string
  url: string
  parentId: string
  children?: TreeItem[]
  hasChildren?: boolean
}

interface AreaItem {
  pkid: string
  areaName: string
  areaCode: string
  parentCode: string
  level: number
  children?: AreaItem[]
}

interface RelationFormData {
  areaId: string
  serviceIds: string[]
}

interface Props {
  visible: boolean
  areaOptions: AreaItem[]
  configTreeData: TreeItem[]
  submitLoading?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', value: RelationFormData): void
  (e: 'close'): void
  (e: 'area-change', areaId: string): void
}

const props = withDefaults(defineProps<Props>(), {
  submitLoading: false
})

const emit = defineEmits<Emits>()

const relationFormRef = ref()
const configTreeRef = ref()
const selectAll = ref(false)
const isIndeterminate = ref(false)

const relationFormData = ref<RelationFormData>({
  areaId: '',
  serviceIds: [],
})

const relationFormRules = {
  areaId: [{ required: true, message: '请选择区域', trigger: 'change' }],
}

const treeProps = {
  children: 'children',
  label: 'name',
}

const handleAreaChange = async (areaId: string) => {
  emit('area-change', areaId)
}

const handleSelectAll = (val: boolean) => {
  if (configTreeRef.value) {
    const allNodeIds = getAllNodeIds(props.configTreeData)
    configTreeRef.value.setCheckedKeys(val ? allNodeIds : [])
    relationFormData.value.serviceIds = val ? allNodeIds : []
  }
  isIndeterminate.value = false
}

// 获取所有节点ID的辅助函数
const getAllNodeIds = (nodes: TreeItem[]): string[] => {
  let ids: string[] = []
  nodes.forEach((node) => {
    ids.push(node.pkid)
    if (node.children && node.children.length > 0) {
      ids = ids.concat(getAllNodeIds(node.children))
    }
  })
  return ids
}

// 更新全选状态
const updateSelectAllStatus = () => {
  const allNodeIds = getAllNodeIds(props.configTreeData)
  const checkedCount = relationFormData.value.serviceIds.length
  const totalCount = allNodeIds.length

  if (checkedCount === 0) {
    selectAll.value = false
    isIndeterminate.value = false
  } else if (checkedCount === totalCount) {
    selectAll.value = true
    isIndeterminate.value = false
  } else {
    selectAll.value = false
    isIndeterminate.value = true
  }
}

const handleTreeCheck = () => {
  if (configTreeRef.value) {
    relationFormData.value.serviceIds = configTreeRef.value.getCheckedKeys()
    updateSelectAllStatus()
  }
}

const handleSubmit = async () => {
  try {
    await relationFormRef.value.validate()
    emit('submit', relationFormData.value)
  } catch (error) {
    // Validation failed
  }
}

const handleCancel = () => {
  emit('update:visible', false)
}

const handleClose = () => {
  relationFormRef.value?.resetFields()
  relationFormData.value = {
    areaId: '',
    serviceIds: [],
  }
  if (configTreeRef.value) {
    configTreeRef.value.setCheckedKeys([])
  }
  selectAll.value = false
  isIndeterminate.value = false
  emit('close')
}

// 设置关系数据
const setRelationData = async (serviceIds: string[]) => {
  relationFormData.value.serviceIds = serviceIds
  await nextTick()
  if (configTreeRef.value) {
    configTreeRef.value.setCheckedKeys(serviceIds)
  }
  updateSelectAllStatus()
}

// 清空关系数据
const clearRelationData = () => {
  relationFormData.value.serviceIds = []
  if (configTreeRef.value) {
    configTreeRef.value.setCheckedKeys([])
  }
  selectAll.value = false
  isIndeterminate.value = false
}

// 重置表单数据
const resetForm = () => {
  relationFormData.value = {
    areaId: '',
    serviceIds: [],
  }
}

// 暴露方法给父组件使用
defineExpose({
  setRelationData,
  clearRelationData,
  resetForm,
  relationFormData
})
</script>

<style scoped lang="scss">
.relation-dialog {
  .config-tree-header {
    margin-bottom: 10px;
    border-bottom: 1px solid #ebeef5;

    .el-checkbox {
      font-weight: 500;
    }
  }

  .config-tree-container {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 8px;
    background-color: #fafafa;

    .el-tree {
      background-color: transparent;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style> 